<?php

namespace App\Http\Controllers\Admin\Access;

use App\Http\Controllers\Admin\BaseController;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Repositories\UserRepositoryEloquent;
use App\Repositories\PermissionRepositoryEloquent;
use App\Http\Requests\Admin\Access\User\CreateRequest;
use App\Http\Requests\Admin\Access\User\UpdateRequest;
use Toastr,Auth,Log;

class UserController extends BaseController
{
    protected $user;

    protected $userRole;

    protected $permission;

    public function __construct(UserRepositoryEloquent $user,PermissionRepositoryEloquent $permission)
    {
        parent::__construct();
        $this->user = $user;
        $this->permission = $permission;

    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $where = [];
        $whereHas = [];
        if($request->has('mobile') && !empty($request['mobile'])){
            $where[] = ['mobile','like','%'.$request['mobile'].'%'];
        }
        if($request->has('name') && !empty($request['name'])){
            $where[] = ['name','like','%'.$request['name'].'%'];
        }
        if($request->has('roleid') && !empty($request['roleid'])){
            $whereHas[] = ['role_id','=',$request['roleid']];

            $users = $this->user
                ->where($where)
                ->whereHas('roles',function($query) use($whereHas){
                            $query->where($whereHas);
                })->paginate(10);
        }else{
            $users = $this->user
                ->where($where)
                ->paginate(10);
        }
        
        return view('admin.access.users.index', compact('users'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        Breadcrumbs::register('admin-user-create', function ($breadcrumbs) {
            $breadcrumbs->parent('admin-user');
            $breadcrumbs->push('添加用户', route('admin.admin_user.create'));
        });
        return view('admin.rbac.admin_users.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(CreateRequest $request)
    {
        //dd($request->all());
        $result = $this->adminUser->store($request->all());
        if(!$result) {
            Toastr::error('新用户添加失败!');
            return redirect(route('admin.admin_user.create'));
        }
        Toastr::success('新用户添加成功!');
        return redirect('admin/admin_user');
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        

        $user = $this->user->find($id);
        //$hasRoles = $user->roles()->lists('name')->toArray();
        //$hasRoles = $user->roles()->lists('name')->toArray();
        $hasRoles = $user->roles()->get()->pluck(['slug'])->toArray();
        
        //var_dump($hasRoles);
        return view('admin.access.users.edit', compact('user', 'hasRoles'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(UpdateRequest $request, $id)
    {
        Log::info('更新用户权限信息.', ['id' => Auth::user()->id]);
        $result = $this->user->update($request->all(), $id);
        if(!$result['status']) {
            Toastr::error($result['msg']);
        } else {
            Toastr::success('用户更新成功');
        }
        return redirect(route('admin.access.users.edit', ['id' => $id]));
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $result = $this->user->delete($id);
        return response()->json($result ? ['status' => 1] : ['status' => 0]);
    }

    /**
     * Delete multi users
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroyAll(Request $request)
    {
        if(!($ids = $request->get('ids', []))) {
            return response()->json(['status' => 0, 'msg' => '请求参数错误']);
        }

        foreach($ids as $id){
            $result = $this->adminUser->delete($id);
        }
        return response()->json($result ? ['status' => 1] : ['status' => 0]);
    }


    /**
     * Display a user's permissions
     * @param $id
     * @return \Illuminate\View\View
     */
    public function permissions($id)
    {
        $user = $this->user->find($id);
        $permissions = $this->permission->topPermissions();

        $userPermissions = $this->user->rolePermissions2($id);
        //dd($userPermissions);
        return view('admin.access.users.permissions', compact('user', 'permissions', 'userPermissions'));
    }

    /**
     * Set role's permissions
     * @param $id
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function storePermissions($id, Request $request)
    {
        $result = $this->user->savePermissions($id, $request->input('permissions', []));
        return response()->json($result ? ['status' => 1] : ['status' => 0]);
    }

}
